import React, { forwardRef, useContext, useEffect, useImperativeHandle, useState } from "react";
import { Button, Container, ListGroup, Offcanvas } from "react-bootstrap";
import ChatService from "../../../services/chatservice";
import AuthenticationContext from "../../../context/Context";
import { group } from "console";
import { PopupDialog } from "../../../components/common";


interface ChatDialogContactListProps{
    ref?:any;
    group?:any
}


const ChatDialogContactList:React.FC<ChatDialogContactListProps> = forwardRef((props:ChatDialogContactListProps,ref)=> {

    const [display,setDisplay] = useState(false);

    const {userInfo} = useContext(AuthenticationContext);
    const [contactList,setContactList] = useState<any>([]);

    useEffect(()=>{
        Promise.all([
            ChatService.getContacts(userInfo.userid),
            ChatService.getGroupMembers((props.group||{}).groupId)]).then(([contactList,members])=>{
                const memberIds = (members||[]).map((member:any,idx:number)=>{
                    return member.userid;
                })
                const cl = contactList.concat([userInfo]).map((contact,idx)=>{
                    return {
                        ...contact,
                        isSelf:contact.userid === userInfo.userid,
                        inGroup:memberIds.includes(contact.userid)
                    }
                })
                setContactList(cl);
            }).catch((err)=>{

            })
    },[])

    useImperativeHandle(ref,()=>{
        return {
            closeContactList,
            showContactList
        }
    })

    const closeContactList = ()=> {
        setDisplay(false);
    }

    const showContactList = ()=> {
        setDisplay(true);
    }

    const addContact = (contact:any)=> {
        ChatService.addContactToGroup({groupId:props.group.groupId,adminId:userInfo.userid,contactId:contact.userid})
        .then(()=>{
          const condition = (ct:any)=>{
            return ct.userid === contact.userid;
          };
          var ctlist = Array.from(contactList);
           const idx:number = ctlist.findIndex(condition)
           if(idx !== -1){
             var obj:any = ctlist[idx];
             obj.inGroup = true;
             ctlist[idx] = obj;
             setContactList(ctlist);
           }
            PopupDialog.showBSPopup({message:`${contact.nickname||contact.username} is Added to group`})
        }).catch((err)=>{
            PopupDialog.showBsError(err);
        })
    }

    return (<Offcanvas placement="end" show={display} onHide={()=>{
        closeContactList();
    }}>
        <Offcanvas.Header closeButton>
            <Offcanvas.Title>Choose a contact to add to this group</Offcanvas.Title>
        </Offcanvas.Header>
        <Offcanvas.Body>
        <div className="d-flex flex-column" style={{height:'100%',width:"100%"}}>
            <ListGroup
                 style={{flex:1,width:"100%"}}>
                    {/* TODO: 将联系人列表提取出去。 */}
                    {contactList.map((contact:any,idx:number)=>{
                        return (<ListGroup.Item key={contact.userid}>
                                <Container fluid className="d-flex flex-row justify-content-between">
                                    <p>{contact.nickname||contact.username}{contact.isSelf && <i style={{fontSize:10}}>(MySelf)</i>}</p>
                                    {(contact.inGroup||contact.isSelf)  ? null:<Button size="sm" onClick={()=>{
                                        addContact(contact)
                                    }}>Add</Button>}
                                </Container>
                            </ListGroup.Item>) 
                    })}
            </ListGroup>
            <Container className="d-flex flex-row justify-content-center">
                <Button variant="none" onClick={closeContactList}>Done</Button>
            </Container>
        </div>
        </Offcanvas.Body>
    </Offcanvas>
)
})

export default ChatDialogContactList;